<?php

class spListCheckbox extends spDiv
{
	public function __construct( $data=null )
	{
		parent::__construct( $data );
		parent::setClass( "spListCheckbox" );
		
		if ( isset($data["list"]) && count($data["list"]) ) 
			$this->addList( $data["list"] );
			
		if ( isset($data["items_selected"] ) )
			$this->selectItems( $data["items_selected"] );
			
		if ( isset($data["csv"]) && count($data["csv"]) ) 
			$this->addCSV( $data["csv"] );				
	}
	
	public function add( $item )
	{
		$data = parent::getData();
		$name = $data["name"];
		
		parent::addChild( new spInputCheckbox( array(
			"name_id"	=> $item["value"],
			"name" 		=> $name."[]",
			"value"		=> $item["value"]
		)));
		
		parent::addChild( new spLabel(array(
			"content" => $item["value"]
		)));
	}	
	
	public function addList( $items )
	{
		$data = parent::getData();
		
		foreach ( $items as $i )
		{
			$checkbox = new spInputCheckbox( array( 
				"name_id"=>$i["value"], 
				"name"=>$data["name"]."[]", 
				"value"=>$i["value"] ) );
		
			$span = new spSpan( /*array( "contentAfter"=>$i["content"] )*/ );
			$span->addStyle( "width", "200px" );
			$span->addStyle( "float", "left" );
			$span->addChild( $checkbox );
			
			$span->addChild( new spLabel( array(
				"content" => $i["content"]
			)));
			
			parent::addChild( $span	);
		}
		
		parent::addChild( new spDiv( array("class"=>"spclear") ) );
	}
	
	public function addCSV( $csv )
	{
		$data = parent::getData();
		$name = $data["name"];
	
		$ar = explode( ",", $csv );
		foreach ( $ar as $a )
		{
			$this->add(array(
				"name"=>$name."[]",
				"value"=>$a
			));
			
			parent::addChild( new spBreak );
		}		
	}	
	
	public function selectItems( $ar )
	{
		foreach ( $ar as $a )
		{
			$checkbox = parent::find($a);
			$checkbox->addAttr( "checked", "checked" );	
		}
	}
	
	public function setElementDataString( $s )
	{
		parent::setElementDataString( $s );
		
		$ar = explode( ",", $s );
		$this->selectItems( $ar );
	}
	
	public function updateFromRequest()
	{
		parent::updateFromRequest();
		
		// convinence variables
		$data = parent::getData();
		$r = $_REQUEST;			

		if ( !isset($data["name"]) )
			return true;
		
		if ( !isset($r[$data["name"]]) )
			return true;

		if ( count($r[$data["name"]])==0 )
			return true;

		// remove empty array elements
		$ar = array_filter( $r[$data["name"]], "spListCheckBoxArrayFilterCompare" );
	
		$this->setElementDataString( implode( ",", $ar ) );
	}
}

function spListCheckBoxArrayFilterCompare( $elem )
{
	if ( $elem=="" )
		return false;
				
	return true;
}

?>